package cloud.shyidong.core.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/5/9
 */
@Slf4j
public class WebUtils {
    
    /**
     * 读取request body
     *
     * @param httpServletRequest
     * @return
     */
    public static String getRequestBody(HttpServletRequest httpServletRequest) {
        StringBuilder sb = new StringBuilder();
        ServletInputStream servletInputStream = null;
        BufferedReader bufferedReader = null;
        try {
            servletInputStream = httpServletRequest.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(servletInputStream));
            String line = bufferedReader.readLine();
            while (ObjectUtils.isNotNull(line)) {
                sb.append(line);
                line = bufferedReader.readLine();
            }
            return sb.toString();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            try {
                if (ObjectUtils.isNotNull(bufferedReader)) {
                    bufferedReader.close();
                }
                if (ObjectUtils.isNotNull(servletInputStream)) {
                    servletInputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    
}
